const app = getApp()
const db = wx.cloud.database()
const _ = db.command

// 日期格式化函数
function formatDate(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return [year, month, day].map(formatNumber).join('-') + ' ' +
        [hour, minute, second].map(formatNumber).join(':');
}

function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
}

Page({
    data: {
        userId: '',
        roomId: '',
        userInfo: {},
        matchUserInfos: [],
        chats: [],
        textInputValue: '',
        page: 1, // 当前页码，初始为 1
        pageSize: 20 // 每页显示的记录数
    },

    onLoad(options) {
        console.log("Received options:", options);
        this.setData({
            userId: app.globalData.userId,
            roomId: options.roomId
        });
        this.initUserInfo();
        this.getHistoryMessages(); // 初始化历史消息
        this.listenForNewMessages(); // 监听新消息
    },

    // 点击了尾部图标
    onClickIcon() {
        wx.chooseImage({
            count: 1,
            success: res => {
                const tempFilePaths = res.tempFilePaths;
                const cloudPath = `images/${Date.now()}-${Math.random()}.png`;
                wx.cloud.uploadFile({
                    cloudPath,
                    filePath: tempFilePaths[0],
                    success: uploadRes => {
                        this.sendImageMessage(uploadRes.fileID);
                    },
                    fail: err => {
                        console.error('图片上传失败:', err);
                        wx.showToast({ title: '图片上传失败', icon: 'none' });
                    }
                });
            },
            fail: err => {
                console.error('选择图片失败:', err);
                wx.showToast({ title: '选择图片失败', icon: 'none' });
            }
        });
    },

    // 发送图片消息
    sendImageMessage(fileID) {
        const { chats, userId, roomId, userInfo } = this.data;
        const show = chats.length === 0 || (Date.now() - (chats[chats.length - 1]?.sendTimeTs || 0) > 120000);
        const message = {
            roomId,
            senderId: userId,
            content: {
                type: 'image',
                value: fileID
            },
            sendTimeTs: Date.now(),
            likeCount: 0,
            collectCount: 0,
            showTime: show,
            nickname: userInfo.nickname
        };

        db.collection('messages').add({
            data: message
        })
        .then(res => {
            console.log('图片消息发送成功:', res);
            message._id = res._id;
            message.formattedSendTime = formatDate(new Date(message.sendTimeTs));
            const newChats = [...chats, message];
            this.setData({
                chats: newChats
            }, () => {
                console.log('更新后的聊天记录:', this.data.chats);
            });
            this.goBottom();
        })
        .catch(err => {
            console.error('图片消息发送失败:', err);
            wx.showToast({ title: '发送失败', icon: 'none' });
        });
    },

    // 获取历史消息
    getHistoryMessages() {
      const that = this;
      const { page, pageSize, roomId } = this.data;
      db.collection('messages')
         .where({ roomId: roomId })
         .orderBy('sendTimeTs', 'asc')
         .skip((page - 1) * pageSize) // 跳过前面的记录
         .limit(pageSize) // 限制返回的记录数
         .get()
         .then(res => {
              const formattedMessages = res.data.map(message => ({
                  ...message,
                  formattedSendTime: formatDate(new Date(message.sendTimeTs))
              }));
              const newChats = [...that.data.chats, ...formattedMessages];
              that.setData({
                  chats: newChats,
                  page: page + 1 // 页码加 1
              }, () => {
                  console.log('初始化聊天记录:', that.data.chats);
              });
          })
         .catch(err => {
              console.error('获取历史消息失败:', err);
          });
  },

    // 滚动到底部加载新的消息
    onReachBottom() {
        this.getHistoryMessages();
    },

    initUserInfo() {
        const that = this;
        db.collection('users').where({ _id: this.data.userId }).get().then(res => {
            if (res.data.length > 0) {
                that.setData({ userInfo: res.data[0] });
            }
        });

        db.collection('chatroomMembers').where({
            roomId: this.data.roomId,
            userId: _.neq(this.data.userId)
        }).get().then(memberRes => {
            const otherUserIds = memberRes.data.map(member => member.userId);
            db.collection('users').where({ _id: _.in(otherUserIds) }).get().then(userRes => {
                that.setData({ matchUserInfos: userRes.data });
            });
        });
    },

    listenForNewMessages() {
        const that = this;
        const watcher = db.collection('messages')
           .where({
                roomId: this.data.roomId,
                sendTimeTs: _.gt(new Date().getTime()) // 监听新消息
            })
           .watch({
                onChange: snapshot => {
                    const newMessages = snapshot.docChanges.filter(change => change.queueType === 'enqueue');
                    newMessages.forEach(message => {
                        const newChats = [...that.data.chats, {
                            ...message.doc,
                            formattedSendTime: formatDate(new Date(message.doc.sendTimeTs))
                        }];
                        that.setData({
                            chats: newChats
                        }, () => {
                            console.log('新消息:', that.data.chats);
                        });
                        that.goBottom();
                    });
                },
                onError: err => {
                    console.error('监听数据库变化失败:', err);
                }
            });
    },

    getContent: function(e) {
        console.log('事件对象 e:', e);

        // 检查 e.detail 的类型，直接获取输入值
        const inputValue = typeof e.detail === 'string' ? e.detail : e.detail.value;

        if (inputValue !== undefined) {
            console.log('输入的值：', inputValue);
            this.setData({
                textInputValue: inputValue
            }, () => {
                console.log('更新后的 textInputValue：', this.data.textInputValue);
            });
        } else {
            console.error('获取输入值失败，事件对象或输入值无效');
        }
    },

    sendMsg() {
        const that = this;
        const { textInputValue, userId, roomId, chats, userInfo } = this.data;

        if (!textInputValue.trim()) {
            wx.showToast({ title: '不能发送空白信息', icon: 'none' });
            return;
        }

        const show = chats.length === 0 || (Date.now() - (chats[chats.length - 1]?.sendTimeTs || 0) > 120000);

        const message = {
            roomId,
            senderId: userId,
            content: {
                type: 'text',
                value: textInputValue
            },
            sendTimeTs: Date.now(),
            likeCount: 0,
            collectCount: 0,
            showTime: show,
            nickname: userInfo.nickname
        };

        db.collection('messages').add({
            data: message
        })
        .then(res => {
            console.log('消息发送成功:', res);
            message._id = res._id;
            message.formattedSendTime = formatDate(new Date(message.sendTimeTs));
            const newChats = [...chats, message];
            that.setData({
                chats: newChats,
                textInputValue: ''
            }, () => {
                console.log('更新后的聊天记录:', that.data.chats);
            });
            that.goBottom();
        })
        .catch(err => {
            console.error('消息发送失败:', err);
            wx.showToast({ title: '发送失败', icon: 'none' });
        });
    },

    goBottom() {
        wx.createSelectorQuery().select('#page').boundingClientRect(function (rect) {
            if (rect) {
                wx.pageScrollTo({
                    scrollTop: rect.height + 4
                });
            }
        }).exec();
    },
    likeMessage(event) {
      const messageId = event.currentTarget.dataset.messageId
      if (!messageId) {
          console.error('messageId is empty');
          return;
      }
      const db = wx.cloud.database();
      const currentUser = this.data.userId;
  
      // 检查用户是否已经点赞
      db.collection('userActions').where({
          userId: currentUser,
          messageId: messageId,
          type: 'like'
      }).get().then(res => {
          if (res.data.length > 0) {
              // 取消点赞
              db.collection('userActions').doc(res.data[0]._id).remove().then(() => {
                  db.collection('messages').doc(messageId).update({
                      data: {
                          likeCount: _.inc(-1)
                      }
                  }).then(() => {
                      wx.showToast({
                          title: '取消点赞成功',
                          icon: 'success'
                      });
                      // 更新本地数据
                      const updatedChats = this.data.chats.map(chat => {
                          if (chat._id === messageId) {
                              chat.likeCount--;
                          }
                          return chat;
                      });
                      this.setData({
                          chats: updatedChats
                      }, () => {
                          console.log('chats after like operation:', this.data.chats);
                      });
                  });
              });
          } else {
              // 点赞
              db.collection('userActions').add({
                  data: {
                      userId: currentUser,
                      messageId: messageId,
                      type: 'like',
                      createdAt: new Date()
                  }
              }).then(() => {
                  db.collection('messages').doc(messageId).update({
                      data: {
                          likeCount: _.inc(1)
                      }
                  }).then(() => {
                      wx.showToast({
                          title: '点赞成功',
                          icon: 'success'
                      });
                      // 更新本地数据
                      const updatedChats = this.data.chats.map(chat => {
                          if (chat._id === messageId) {
                              chat.likeCount++;
                          }
                          return chat;
                      });
                      this.setData({
                          chats: updatedChats
                      }, () => {
                          console.log('chats after like operation:', this.data.chats);
                      });
                  });
              });
          }
      });
  },
  
  collectMessage(event) {
      const messageId = event.currentTarget.dataset.messageId;
      if (!messageId) {
          console.error('messageId is empty');
          return;
      }
      const db = wx.cloud.database();
      const currentUser = this.data.userId;
  
      // 检查用户是否已经收藏
      db.collection('userActions').where({
          userId: currentUser,
          messageId: messageId,
          type: 'collect'
      }).get().then(res => {
          if (res.data.length > 0) {
              // 取消收藏
              db.collection('userActions').doc(res.data[0]._id).remove().then(() => {
                  db.collection('messages').doc(messageId).update({
                      data: {
                          collectCount: _.inc(-1)
                      }
                  }).then(() => {
                      wx.showToast({
                          title: '取消收藏成功',
                          icon: 'success'
                      });
                      // 更新本地数据
                      const updatedChats = this.data.chats.map(chat => {
                          if (chat._id === messageId) {
                              chat.collectCount--;
                          }
                          return chat;
                      });
                      this.setData({
                          chats: updatedChats
                      }, () => {
                          console.log('chats after collect operation:', this.data.chats);
                      });
                  });
              });
          } else {
              // 收藏
              db.collection('userActions').add({
                  data: {
                      userId: currentUser,
                      messageId: messageId,
                      type: 'collect',
                      createdAt: new Date()
                  }
              }).then(() => {
                  db.collection('messages').doc(messageId).update({
                      data: {
                          collectCount: _.inc(1)
                      }
                  }).then(() => {
                      wx.showToast({
                          title: '收藏成功',
                          icon: 'success'
                      });
                      // 更新本地数据
                      const updatedChats = this.data.chats.map(chat => {
                          if (chat._id === messageId) {
                              chat.collectCount++;
                          }
                          return chat;
                      });
                      this.setData({
                          chats: updatedChats
                      }, () => {
                          console.log('chats after collect operation:', this.data.chats);
                      });
                  });
              });
          }
      });
  }
})